/*
 * Alberto Ruiz-Larrea Guillén...11383
 * Erdi Dogruel..................14955
 * Marcos Pérez Martín...........10324
 */

package com.example.androball_manager;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.example.database.OpenDB;
import com.example.database.getYourTeamString;

public class MainActivity extends Activity {

	private OpenDB db = new OpenDB(this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// load Database in Application
		try {

			db.createDataBase();

		} catch (IOException ioe) {

			throw new Error("Unable to create database");

		}

		try {

			db.openDataBase();

		} catch (SQLException sqle) {

			throw sqle;

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void go_to_FirstMenu(View view) {
		// Shows error if you have no started league
		getYourTeamString g = new getYourTeamString();
		String S = "null";
		try {
			S = (g.execute(db).get().toString());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (S.length() <= 5) {
			alert();
		} else {
			Intent intent = new Intent(this, FirstMenuActivity.class);
			startActivity(intent);
		}
	}

	public void alert() {

		new AlertDialog.Builder(this)
				.setTitle(R.string.title)
				.setMessage(R.string.message)
				.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {

							}
						})

				.setIcon(android.R.drawable.ic_dialog_alert).show();
	}

	/*
	 * start new game
	 */
	public void createNewGame(View view) {
		Intent intent = new Intent(this, SelectTeamActivity.class);
		startActivity(intent);
	}

	@Override
	public void onBackPressed() {
		return;
	}

}
